
// 渲染页面-----------------------------------------------------------------------------------

// 封装函数
function renderPage() {
  axios.get('/my/category/list',).then(function (res) {
    console.log(res.data.data);
    let str = ''
    res.data.data.forEach(item => {
      console.log(item);
      str += `
        <tr>
          <td>${item.name}</td>
          <td>${item.alias}</td>
          <td>
            <button type="button" class="layui-btn layui-btn-xs">编辑</button>
            <button type="button" class="del layui-btn layui-btn-xs layui-btn-danger" data-id="${item.id}" data-name="${item.name}" data-alias="${item.alias}">删除</button>
          </td>
        </tr>
      `
    })
    $('tbody').html(str)
  })
}

renderPage()

// 删除功能------------------------------------------------------------------------------------
$('tbody').on('click', 'button:contains("删除")', function () {
  let id = $(this).data('id')
  console.log(id, typeof id);
  layer.confirm('确认删除吗?', index => {
    axios.get(`/my/category/delete?id=${id}`).then(res => {
      let { status, message } = res.data
      if (status === 0) {
        layer.msg(message)
        renderPage()
      }
    })
  })
})

// 添加类别------------------------------------------------------------------------------------
let addIndex
$('button:contains("添加类别")').on('click', function () {

  addIndex = layer.open({
    type: 1,
    area: ['500px', '250px'],
    title: '添加分类',
    content: $('#tpl-add').html()
  })

  $('body').on('submit', '#form-add', function (e) {
    e.preventDefault()
    let data = $(this).serialize()
    axios.post('/my/category/add', data).then(res => {
      let { status, message } = res.data
      console.log(status);
      if (status === 0) {
        layer.close(addIndex)
        layer.msg(message)
        renderPage()

      }
    })
  })

})

// 编辑功能-------------------------------------------------------------------------------------
let editIndex
$('tbody').on('click', 'button:contains("编辑")', function () {
  editIndex = layer.open({
    type: 1,
    area: ['500px', '250px'],
    title: '编辑分类',
    content: $('#tpl-edit').html()
  })

  // 数据回填
  let data = $(this).next().data()
  let form = layui.form
  form.val('formDemo', data)

})
// 发送请求
$('body').on('submit', '#form-edit', function (e) {
  e.preventDefault()
  let data = $(this).serialize()
  axios.post('/my/category/update', data).then(res => {
    console.log(res);
    let { status, message } = res.data
    if (status === 0) {
      layer.msg(message)
      layer.close(editIndex)
      renderPage()
    }
  })
})